﻿using Freshbox2._0.BLL;
using Freshbox2._0.MODEL;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace Freshbox2._0.UI.Controllers
{
    public class PresellWaresController : BaseController<presellwares>
    {
        //
        // GET: /PresellWares/

        //public ActionResult Index()
        //{
        //    return View();
        //}

        public override BLL.BaseBll<presellwares> bll
        {
            get
            {
                return new PresellWaresBll();
            }

        }

        StoreBll storeBll = new StoreBll();

        PwaresStandardBll standardBll = new PwaresStandardBll();

        PwaresTypeBll typeBll = new PwaresTypeBll();

        //pwaresId   pwaresName  pwaresStatus pwaresCreatime pwaresPrice  pwaresDescription  pwaresNum  pwaresStoreName  pwaresTypeName   pwaresStandardName  pwaresPicUrl
        public class PresellWaresModel
        {
            public long pwaresId;
            public string pwaresName;
            public string pwaresStatus;
            public string pwaresCreatime;
            public decimal? pwaresPrice;
            public decimal? pwaresDisCount;
            public string pwaresDescription;
            public int? pwaresNum;
            public string pwaresStoreName;
            public string pwaresTypeName;
            public string pwaresStandardName;
            public string pwaresPicUrl;
        }

        public class GetOneModel
        {
            public long pwaresId;
            public string pwaresName;
            public int? pwaresStatus;
            public DateTime pwaresCreatime;
            public decimal? pwaresPrice;
            public decimal? pwaresDisCount;
            public string pwaresDescription;
            public int? pwaresNum;
            public string pwaresStoreName;
            public int? pwaresStoreID;
            public string pwaresTypeName;
            public int? pwaresTypeID;
            public string pwaresStandardName;
            public string pwaresStandardId;
            public string[] ids;
            public string pwaresPicUrl;
        }


        //加载数据列表 查询方法     

        public override ActionResult Get(int page, int rows, presellwares model)
        {
            int count;
            var waresList = new List<PresellWaresModel>();

            var list = bll.Search(model, x=>x.pwaresStatus==1,true, x=>x.pwaresId, rows, page, out count).ToList().Select(x => new
            {
                x.pwaresId,
                x.pwaresName,
                pwaresStatus = x.pwaresStatus == 1 ? "有效" : "已下架",
                x.pwaresPrice,
                x.pwaresCreatime,
                x.pwaresDescription,
                x.pwaresNum,
                x.pwaresStandardId,
                x.pwaresStoreid,
                x.pwaresTypeId,
                x.pwaresPicUrl,
                x.pwaresDisCount,
            }).ToList();
            foreach (var item in list)
            {
                PresellWaresModel waresModel = new PresellWaresModel();
                waresModel.pwaresId = item.pwaresId;
                waresModel.pwaresName = item.pwaresName;
                waresModel.pwaresPrice = item.pwaresPrice;
                waresModel.pwaresNum = item.pwaresNum;
                waresModel.pwaresDescription = item.pwaresDescription;
                waresModel.pwaresCreatime = item.pwaresCreatime.ToString("yyyy-MM-dd HH:mm:ss");
                waresModel.pwaresStatus = item.pwaresStatus;
                waresModel.pwaresPicUrl = item.pwaresPicUrl;
                waresModel.pwaresDisCount = item.pwaresDisCount;
                var name = "";
                var storeList= storeBll.Search(x => x.storeid == item.pwaresStoreid).Select(x => new { x.storeid, x.storeName }).ToList();
                 if (storeList.Count() != 0)
                {
                    name = storeList.FirstOrDefault().storeName;
                }
                waresModel.pwaresStoreName = name;

                waresModel.pwaresStandardName = item.pwaresStandardId;
                if (string.IsNullOrEmpty(item.pwaresStandardId))
                {
                    waresModel.pwaresStandardName = "";
                }
                else
                {
                    string standName1 = "";
                    string str = item.pwaresStandardId;
                    string[] str_arr = str.Split(',');
                    foreach (var a in str_arr)
                    {
                        int id = Convert.ToInt32(a);
                        string standName = standardBll.Search(x => x.pwaresStandardId == id).Select(x => new { x.pstandardName }).FirstOrDefault().pstandardName + ",";

                        standName1 = standName1 + standName;


                    }
                    standName1 = standName1.Remove(standName1.LastIndexOf(","), 1);
                    waresModel.pwaresStandardName = standName1;
                }
                var typelist = typeBll.Search(x => x.pwaresTypeId == item.pwaresTypeId).Select(x => new { x.pwaresTypeName });
                if (typelist.Count()!=0)
                {
                    waresModel.pwaresTypeName =typelist.FirstOrDefault().pwaresTypeName;

                }

                waresList.Add(waresModel);
            }

            return Json(new { total = count, rows = waresList });
        }


        //新增类型信息
        [HttpPost]
        public override ActionResult Save(presellwares model)
        {
            string msg = "";
            int result = 0;
            int jieguo = 1;
            if (model.pwaresName != "" && model.pwaresName != "")
            {
                model.pwaresStatus = 1;
                model.pwaresCreatime = DateTime.Now;
                model.pwaresPicUrl = "http://console.shiyispace.com/" + model.pwaresPicUrl.Substring(1);
                if (String.IsNullOrEmpty(model.pwaresStandardId))
                {
                    model.pwaresStandardId = "";
                }
                else
                {
                    model.pwaresStandardId = model.pwaresStandardId;//.Substring(1)
                }
    
                if (bll.Add(model) > 0)
                {
                    msg = "添加成功";
                    result = 1;
                    jieguo = 1;
                    return Json(new { jieguo = jieguo, state = result, msg = msg });
                }
                else
                {
                    jieguo = 0;
                    msg = "添加失败";
                    return Json(new { jieguo = jieguo, state = result, msg = msg });
                }
            }
            else
            {
                jieguo = 0;
                msg = "请填写完整";
                return Json(new { jieguo = jieguo, state = result, msg = msg });
            }

        }


        public ActionResult GetStore()
        {
                return Json(storeBll.Search(x => x.storeStatus == 1).Select(x => new { StoreID = x.storeid, StoreName = x.storeName }).ToList(), JsonRequestBehavior.AllowGet);

        }
        public ActionResult GetWaresType()
        {
            return Json(typeBll.Search(x => x.pwaresTypeStatus == 1).Select(x => new { TypeID = x.pwaresTypeId, TypeName = x.pwaresTypeName }).ToList(), JsonRequestBehavior.AllowGet);

        }
        public ActionResult GetWaresStandard()
        {
            return Json(standardBll.Search(x => x.pstandardStatus == 1).Select(x => new { StandardID = x.pwaresStandardId, StandardName = x.pstandardName }).ToList(), JsonRequestBehavior.AllowGet);

        }

        [HttpPost]
        public string PostExcelData()
        {
            //获取客户端上传的文件集合
            HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
            //获取文件集合中的第一个文件(每次只上传一个文件)
            HttpPostedFile file = files[0];
            //定义文件存放的目标路径
            string targetDir = System.Web.HttpContext.Current.Server.MapPath("~/Images");

            //组合成文件的完整路径
            string path = System.IO.Path.Combine(targetDir, System.IO.Path.GetFileName(file.FileName));
            //保存上传的文件到指定路径中
            file.SaveAs(path);
            return path;
        }


        public ActionResult Modify2(presellwares model)
        {
            string msg = "修改失败";
            string state = "false";

            model.pwaresStatus = 1;
            model.pwaresCreatime = DateTime.Now;
            model.pwaresStandardId = model.pwaresStandardId;          //.Substring(1);
            if (model.pwaresPicUrl !=null)
            {

               string  a =  model.pwaresPicUrl.Substring(1);
               string b = "http://console.shiyispace.com/" + a;
               model.pwaresPicUrl = b;
            }
            
            if (model.pwaresName != "" && model.pwaresName != null && model.pwaresPrice != 0 && model.pwaresPrice != null)
            {
                if (bll.Modify(model) > 0)
                {
                    msg = "修改成功";
                    state = "true";
                }
            }
            else
            {
                msg = "请填写完整";
                state = "false";
            }

            return Json(new { state = state, msg = msg });
        }

        List<GetOneModel> oneList = new List<GetOneModel>();
        //获取选中的一条数据   
        public ActionResult GetOnlyOne(long id)
        {
            // return Json(bll.Search(x => x.areaMaID == id).ToList().Select(x => new { x.areaMaID,x.userPhone, x.name, x.userName, x.userPass, x.areaCode, }).ToList()[0], JsonRequestBehavior.AllowGet);
            var list = bll.Search(x => x.pwaresId == id).ToList().Select(x => new { x.pwaresId, x.pwaresName, x.pwaresNum, x.pwaresPicUrl,x.pwaresDisCount, x.pwaresCreatime, x.pwaresPrice, x.pwaresDescription, x.pwaresStandardId, x.pwaresStoreid, x.pwaresTypeId, x.pwaresStatus }).ToList();
            foreach (var item in list)
            {
                string typeName = "";
                var type = typeBll.Search(x => x.pwaresTypeId == item.pwaresTypeId).Select(x => new { TypeID = x.pwaresTypeId, TypeName = x.pwaresTypeName }).ToList();
                if (type.Count() != 0)
                {
                    typeName = type.FirstOrDefault().TypeName;
                }
                string storeName = "";
                var store = storeBll.Search(x => x.storeid == item.pwaresStoreid).Select(x => new { StoreID = x.storeid, StoreName = x.storeName }).ToList();
                if (store.Count() != 0)
                {
                    storeName = store.FirstOrDefault().StoreName;
                }

                GetOneModel model = new GetOneModel();
                model.pwaresTypeID = item.pwaresTypeId;
                model.pwaresStoreID = item.pwaresStoreid;
                model.pwaresId = item.pwaresId;
                model.pwaresName = item.pwaresName;
                model.pwaresNum = item.pwaresNum;
                model.pwaresPicUrl = item.pwaresPicUrl;
                model.pwaresPrice = item.pwaresPrice;
                model.pwaresDisCount = item.pwaresDisCount;
                model.pwaresStandardId = item.pwaresStandardId;
                string standName1 = "";
     
                if (string.IsNullOrEmpty(item.pwaresStandardId))
                {
                    model.pwaresStandardName = "";
                }
                else
                {
                    string str = item.pwaresStandardId;
                    string[] str_arr = str.Split(',');

                    foreach (var a in str_arr)
                    {
                        int ida = Convert.ToInt32(a);
                        string standName = standardBll.Search(x => x.pwaresStandardId == ida).Select(x => new { x.pstandardName }).FirstOrDefault().pstandardName + ",";
                        standName1 = standName1 + standName;
                      

                    }
                    standName1 = standName1.Remove(standName1.LastIndexOf(","), 1);
                    model.pwaresStandardName = standName1;
                    model.ids = str_arr;
                }

               // model.pwaresStandardName = item.pwaresStandardId;
                model.pwaresStoreName = storeName;
                model.pwaresTypeName = typeName;
                model.pwaresStatus = item.pwaresStatus;
                model.pwaresCreatime = item.pwaresCreatime;
                model.pwaresDescription = item.pwaresDescription;
                oneList.Add(model);

            }
            return Json(oneList.ToList()[0], JsonRequestBehavior.AllowGet);
        }

        //下架商品    修改状态为
        public ActionResult ModifyState(int id)
        {
            string msg = "商品下架失败";
            string state = "false";

            var oneList = bll.Search(x => x.pwaresId == id).Select(x => new { x.pwaresId, x.pwaresName, x.pwaresNum, x.pwaresPicUrl, x.pwaresStatus, x.pwaresStandardId, x.pwaresStoreid, x.pwaresTypeId,x.pwaresCreatime,x.pwaresDescription,}).ToList();

            presellwares model = new presellwares();
            model.pwaresId = oneList.FirstOrDefault().pwaresId;
            model.pwaresName = oneList.FirstOrDefault().pwaresName;
            model.pwaresNum = oneList.FirstOrDefault().pwaresNum;
            model.pwaresPicUrl = oneList.FirstOrDefault().pwaresPicUrl;
            model.pwaresStandardId = oneList.FirstOrDefault().pwaresStandardId;
            model.pwaresStoreid = oneList.FirstOrDefault().pwaresStoreid;
            model.pwaresTypeId = oneList.FirstOrDefault().pwaresTypeId;
            model.pwaresCreatime = oneList.FirstOrDefault().pwaresCreatime;
            model.pwaresDescription = oneList.FirstOrDefault().pwaresDescription;
            model.pwaresStatus = 0;

            if (bll.Modify(model) > 0)
            {
                msg = "商品下架成功";
                state = "true";
            }
            return Json(new { state = state, msg = msg });
        }


        public ActionResult PostImg()
        {
            //HttpFileCollectionBase files = Request.Files;
            //HttpPostedFileBase File = files["File"];
            //string FileName = File.FileName; //上传的原文件名  
            //string guid = "";
            //if (FileName != null && FileName != "")
            //{
            //    string FileType = FileName.Substring(FileName.LastIndexOf(".") + 1); //得到文件的后缀名  
            //    guid = System.Guid.NewGuid().ToString() + "." + FileType; //得到重命名的文件名  
            //    File.SaveAs(Server.MapPath("/Images/") + guid); //保存操作  
            //}
            //return Json("~/Images/" + guid);


            //var file = Request.Files["fileMenuIcon"];
            
            //if (file == null)
            //{
            //    return Content("error");
            //}
            //string path = "/Images/" + Guid.NewGuid().ToString() + "-" + file.FileName;
            //file.SaveAs(Request.MapPath(path));
            //return Content(path);


            HttpFileCollectionBase files = Request.Files;
            HttpPostedFileBase File = files["pwaresPicUrl"];
            string FileName = File.FileName; //上传的原文件名  
            string guid = "";
            if (FileName != null && FileName != "")
            {
                string FileType = FileName.Substring(FileName.LastIndexOf(".") + 1); //得到文件的后缀名  
                guid = System.Guid.NewGuid().ToString() + "." + FileType; //得到重命名的文件名  
                File.SaveAs(Server.MapPath("/Images/") + guid); //保存操作  
            }
            return Json("~/Images/" + guid);
        }

    }
}
